import java.util.*;

public class Solution721 {
    public List<List<String>> accountsMerge(List<List<String>> accounts) {
        Map<String,Map<String,String>> map=new HashMap<>();
        for (List<String> account : accounts) {
            String name=account.get(0);
            Map<String,String> m=map.getOrDefault(name,new HashMap<>());
            if (!m.containsKey(account.get(1))){
                m.put(account.get(1),account.get(1));
            }
            String t=find(m,account.get(1));
            for (int i=2;i<account.size();i++){
                if (!m.containsKey(account.get(i))){
                    m.put(account.get(i),account.get(i));
                }
                String s1=find(m,account.get(i));
                if (!t.equals(s1)){
                    m.put(s1,t);
                }
            }
            map.put(name,m);
        }
        List<List<String>> ans=new ArrayList<>();
        for (Map.Entry<String, Map<String, String>> stringListEntry : map.entrySet()) {
            Map<String,String> m=stringListEntry.getValue();
            Set<String> set=new HashSet<>();
            for (Map.Entry<String, String> stringStringEntry : m.entrySet()) {
                if (!set.contains(stringStringEntry.getKey())){
                    String s=find(m,stringStringEntry.getKey());
                    List<String> a=new ArrayList<>();
                    for (Map.Entry<String, String> stringEntry : m.entrySet()) {
                        if (find(m,stringEntry.getKey()).equals(s)){
                            a.add(stringEntry.getKey());
                            set.add(stringEntry.getKey());
                        }
                    }
                    a.sort(String::compareTo);
                    a.add(0,stringListEntry.getKey());
                    ans.add(a);
                }
            }
        }
        return ans;
    }

    String find(Map<String,String> map,String s){
        while (!map.get(s).equals(s)){
            s=map.get(s);
        }
        return s;
    }

    public static void main(String[] args) {
        List<String> l1=new ArrayList<>();
        l1.add("John");l1.add("johnsmith@mail.com");l1.add("john00@mail.com");
        List<String> l2=new ArrayList<>();
        l2.add("John");l2.add("johnnybravo@mail.com");
        List<String> l3=new ArrayList<>();
        l3.add("John");l3.add("johnsmith@mail.com");l3.add("john_newyork@mail.com");
        List<String> l4=new ArrayList<>();
        l4.add("Mary");l4.add("mary@mail.com");
        List<List<String>> lists=new ArrayList<>();
        lists.add(l1);lists.add(l2);lists.add(l3);lists.add(l4);
        List<List<String>> ls=new Solution721().accountsMerge(lists);
        for (List<String> l : ls) {
            System.out.println(l);
        }
    }
}
